import { Base } from "../util"

export class Masek extends Base {
	image;
	x;
	y;
	size;
	constructor({ ctx, imgUrl, x, y, width, height, fuzziness }) {
		super(ctx)
		if (typeof x !== 'number' || typeof y !== 'number' || typeof width !== "number" || typeof height !=="number" || typeof fuzziness !== 'number') throw Error("you should provide params x,y,size,fuzziness!")
		this.x = x
		this.y = y
		this.width = width
		this.height = height
		this.fuzziness = fuzziness
		let img = new Image()
		img.crossOrigin = 'anonymous'
		let imageStatus = new Promise((resolve, reject) => {
			img.onload = () => {
				this.image = img
				this.draw(x, y, width, height)
				resolve(img)
			}
			img.onerror = () => {
				console.error("image can't requested")
				reject("image can't requeste")
			}
		})
		this.imageStatus = imageStatus
		img.src = imgUrl
	}
	init() {
		this.ctx.canvas.width = this.image.width
		this.ctx.canvas.height = this.image.height
		this.ctx.drawImage(this.image, 0, 0, this.image.width, this.image.height)
	}
	draw(x, y, width, height) {
		this.init()
		let imageData = this.getFrameImageData()
		for (let i = 0; i < width; i++) {
			let xaxis = (i / this.fuzziness) >> 0
			for (let j = 0; j < height; j++) {
				let yaxis = (j / this.fuzziness) >> 0
				// y 取整 * fuzziness 
				let { data: [r, g, b, a] } = this.getPxImageData({ x: x + xaxis * this.fuzziness, y: y + yaxis * this.fuzziness })
				let startIndex = y * this.image.width * 4 + x * 4 + j * this.image.width * 4 + i * 4
				imageData.data[startIndex] = r
				imageData.data[startIndex + 1] = g
				imageData.data[startIndex + 2] = b
				imageData.data[startIndex + 3] = a
			}
		}
		this.ctx.putImageData(imageData, 0, 0)
	}
}